package com.baidu.qianfan.controller;

import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/test")
public class testMongoDBController {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 插入数据
     */
    @PostMapping("/insert")
    public String insert() {
        MongoCollection<Document> collection = mongoTemplate.getCollection("testcollection");
        Document document = new Document("name", "testfile")
                .append("age", 18)
                .append("email", "11111@qq.com");
        collection.insertOne(document);
        return "插入数据成功";
    }

    /**
     * 查询数据
     */
    @GetMapping("/get")
    public List<Document> get() {
        MongoCollection<Document> collection = mongoTemplate.getCollection("testcollection");
        FindIterable<Document> documents = collection.find(Filters.eq("name", "testfile"));
        return documents.into(new ArrayList<>());
    }

    /**
     * 修改数据
     */
    @PutMapping("/update")
    public String update() {
        MongoCollection<Document> collection = mongoTemplate.getCollection("testcollection");
        collection.updateOne(Filters.eq("name", "testfile"), Updates.set("age", 22));
        return "更新数据成功";
    }

    /**
     * 删除文件file
     */
    @DeleteMapping("/delete")
    public String delete() {
        MongoCollection<Document> collection = mongoTemplate.getCollection("testcollection");
        collection.deleteOne(Filters.eq("name", "testfile"));
        return "删除文件";
    }


}
